import 'package:flutter/cupertino.dart';
import 'package:logger/logger.dart';
import 'index.dart';

// 路由监听
class RouteObservers<R extends Route<dynamic>> extends RouteObserver<R> {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPush(route, previousRoute);
    var name = route.settings.name ?? '';
    if (name.isNotEmpty) RouterPages.history.add(name);
    Logger().d('didPush');
    Logger().d(RouterPages.history);
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPop(route, previousRoute);
    RouterPages.history.remove(route.settings.name);
    Logger().d('didPop');
    Logger().d(RouterPages.history);
  }

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    if (newRoute != null) {
      var index = RouterPages.history.indexWhere((element) {
        return element == oldRoute?.settings.name;
      });
      var name = newRoute.settings.name ?? '';
      if (name.isNotEmpty) {
        if (index > 0) {
          RouterPages.history[index] = name;
        } else {
          RouterPages.history.add(name);
        }
      }
    }
    Logger().d('didReplace');
    Logger().d(RouterPages.history);
  }

  @override
  void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didRemove(route, previousRoute);
    RouterPages.history.remove(route.settings.name);
    Logger().d('didRemove');
    Logger().d(RouterPages.history);
  }

  // @override
  // void didStartUserGesture(
  //     Route<dynamic> route, Route<dynamic>? previousRoute) {
  //   super.didStartUserGesture(route, previousRoute);
  // }

  // @override
  // void didStopUserGesture() {
  //   super.didStopUserGesture();
  // }
}
